import storage from 'store'
import store from '@/store'
import expirePlugin from 'store/plugins/expire'
import { login, logout } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

// import { generatorDynamicRouter } from '@/router/generator-routers'

storage.addPlugin(expirePlugin)
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 登录
    Login ({ commit }, Params) {
      return new Promise((resolve, reject) => {
        login(Params).then(response => {
          if (response.code == 200) {
            const data = response.data
            // token 7天过期
            // storage.set(ACCESS_TOKEN, data.token, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
            // 设置2小时过期
            // storage.set(ACCESS_TOKEN, data.token, new Date().getTime() + 1000 * 60 * 60 * 2)
            const expireTime = new Date().getTime() + 1000 * 60 * 60 * 1
            storage.set(ACCESS_TOKEN, data.token, expireTime)
            localStorage.setItem('expire_time', expireTime)
            localStorage.setItem('info', JSON.stringify(data))
            commit('SET_TOKEN', data.token)
            commit('SET_INFO', data)
            commit('SET_NAME', { name: data.presentTitle, welcome: welcome() })
            commit('SET_AVATAR', 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png')
          }

          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 退出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          store.commit('SET_ROUTERS', [])
          localStorage.setItem('expire_time', '')
          localStorage.setItem('info', '')
          storage.remove(ACCESS_TOKEN)
          setTimeout(() => {
            window.location.reload()
          }, 300)
          resolve()
        }).catch((err) => {
          console.log('logout fail:', err)
        }).finally(() => {
        })
      })
    }

  }
}

export default user
